package com.common.util;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * 文件上传、下载工具类
 */
public class UpDownUtil {

    /**
     * 保存文件，直接以multipartFile形式
     * @param multipartFile
     * @param path 文件保存绝对路径
     * @return 返回文件名
     * @throws IOException
     */
    public static String saveFile(MultipartFile multipartFile, String path,String fileName) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        InputStream inputStream = multipartFile.getInputStream();
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = inputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return fileName;
    }

    /**
     * 文件下载
     */
    public static String download(File file, HttpServletResponse response) {
        String msg = "";
        String fileName = file.getName();
        System.out.println("path = "+file.getAbsolutePath());
        try {
            InputStream inStream = new FileInputStream(file);
            msg = download(inStream, fileName, response);
        } catch (Exception e) {
            System.out.println("系统找不到指定路径");
            msg = "下载失败，系统找不到指定路径";
        }
        return msg;
    }

    /**
     * 文件下载
     */
    public static String download(InputStream inStream,String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        String msg = "";
        response.setContentType("text/html; charset=UTF-8"); //设置编码字符
        response.setContentType("application/octet-stream"); //设置内容类型为下载类型
        response.setHeader("Content-disposition","attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        try {
            OutputStream os = response.getOutputStream();
            byte[] buff = new byte[1024];
            int len = -1;
            while ((len = inStream.read(buff)) > 0) {
                os.write(buff, 0, len);
            }
            os.flush();
            os.close();
            inStream.close();
            msg = "下载成功";
        } catch (Exception e) {
            System.out.println("系统找不到指定路径");
            msg = "下载失败，系统找不到指定路径";
        }
        return msg;
    }
}
